package org.mindrive.system.util;

import lombok.extern.slf4j.Slf4j;
import org.mindrive.system.core.MindriveException;

import java.lang.reflect.Field;
import java.util.Date;

@Slf4j
public class DefaultUtil {

    public static void setDefaultValue(Object obj) {
        if (obj == null) {
            throw new MindriveException("实例不存在");
        }
        // 获取所有属性
        Field[] currentFields = obj.getClass().getDeclaredFields();

        for (Field field : currentFields) {

            try {
                field.setAccessible(true);
                if (field.getName().equals("id")) {
                    continue;
                }
                Object val = null;
                try {
                    val = field.get(obj);
                } catch (Exception ex) {
                    log.error("取得类属性值失败。", ex);
                }

                if (val == null) {
                    if (String.class.equals(field.getType())) {
                        field.set(obj, "");
                    }

                    if (Integer.class.equals(field.getType())) {
                        field.set(obj, 0);
                    }

                    if (Boolean.class.equals(field.getType())) {
                        field.set(obj, false);
                    }
                    if (Date.class.equals(field.getType())) {
                        field.set(obj, null);
                    }
                }

            } catch (IllegalAccessException e) {
                log.error("初期化属性失败。[{}]", field.getName(), e);
            }

        }
    }

}
